<?php
/** 多多进宝 */

namespace App\Services;


use GuzzleHttp\Client;
use Log;

class PddInterface
{
    const API_URL = "https://gw-api.pinduoduo.com/api/router";

    /**
     * @var self[私有化实例]
     */
    protected static $instance;

    /**
     * 参数
     *
     * @var array
     */
    protected static $param = [];

    /**
     * 构造函数
     *
     * DuoduoInterface constructor.
     */
    public function __construct()
    {
        self::$param['client_id'] = '5798ae0ec02a4832b4adfa49d99a2523';
        self::$param['sign_method'] = 'md5';
        self::$param['timestamp'] = strval(time());
    }

    private function __clone()
    {

    }

    /**
     * 实例化对象
     * @param $param
     * @return PddInterface
     */
    public static function getInstance($param = [])
    {
        // 数据格式化
        foreach ($param as $k => &$v){
            if (is_array($v)){
                $param[$k] = json_encode($v);
            }
        }

        self::$param = $param;

        if (!(self::$instance instanceof self)) {
            self::$instance = new static();
            return self::$instance;
        } else {
            return null;
        }
    }

    /**
     * 销毁实例
     */
    public static function delInstance()
    {
        self::$instance = null;
    }

    /**
     * @param $params
     * @return string
     */
    private function signature($params)
    {
        ksort($params);
        $string = '';
        array_walk($params, function ($item, $key) use (&$string) {
            $string .= sprintf('%s%s', $key, $item);
        });

        $client_secret = '52f2bb15a410f21233d853582f175e30f8c613c8';
        return strtoupper(md5(sprintf('%s%s%s', $client_secret, $string, $client_secret)));
    }

    /**
     * @param $method
     * @param string $data_type
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function request($method, $data_type = 'JSON')
    {
        self::$param['type'] = $method;
        self::$param['data_type'] = $data_type;
        self::$param['sign'] = $this->signature(self::$param);
        $client = new Client(['headers' => ['Content-Type' => 'application/json']]);
        $res = $client->request('POST', self::API_URL, [
            'form_params' => self::$param,
            'timeout' => 3,
        ]);
        $response = json_decode($res->getBody(), true);
        if (isset($response['error_response'])) {
            Log::info('Fail to call api');
            throw new \Exception($response['error_response']['error_msg'], $response['error_response']['error_code']);
        }
        return $response;
    }
}